import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './user.entity';
import { pagination, paginationInterfacesImpl } from '../utils/pagination';

const { getDate } = require('../utils/tool');
const { updateUserError } = require('../provider/error');

@Injectable()
export class UsersService {
  constructor(
    @InjectRepository(User) private usersRepository: Repository<User>,
  ) {}

  // 获取所有用户
  async findAll(pageParam): Promise<paginationInterfacesImpl> {
    return await pagination(pageParam, this.usersRepository, 'user');
  }

  async updateUser(userInfo) {
    const { id } = userInfo;
    const res = await this.usersRepository.update(id, {
      ...userInfo,
    });
    if (res.affected == 0) return updateUserError();
    return [];
  }

  async getUserInfo(user_id) {
    const res = await this.usersRepository.findOne({ where: { id: user_id } });
    res.create_time = getDate(res.create_time, 0);
    res.updated_time = getDate(res.updated_time, 0);
    return res;
  }
}
